<template>
  <div class="learning-view-container">
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>加载学习内容中...</p>
    </div>
    
    <div v-else-if="error" class="error-message">
      <p>{{ error }}</p>
      <button @click="fetchLearningStep" class="btn-retry">重试</button>
    </div>
    
    <div v-else class="learning-content">
      <!-- 顶部进度条 -->
      <div class="progress-bar-container">
        <div class="progress-info">
          <div class="back-button" @click="goBack">
            <span class="back-icon">←</span> 返回学习路径
          </div>
          <div class="progress-text">
            <span class="current-step">{{ currentStepIndex + 1 }}</span> / {{ totalSteps }} 
            <span class="stage-name">{{ currentStage ? currentStage.title : '' }}</span>
          </div>
        </div>
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: `${progressPercentage}%` }"></div>
        </div>
      </div>
      
      <!-- 学习内容区域 -->
      <div class="learning-main">
        <div class="step-header">
          <h1>{{ currentStep ? currentStep.title : '开始学习' }}</h1>
          <div class="step-meta">
            <span class="estimated-time">预计用时: {{ currentStep ? currentStep.estimatedTime : 0 }}分钟</span>
            <span class="step-type" v-if="stepType === 'card'">知识卡片</span>
            <span class="step-type" v-else-if="stepType === 'exercise'">练习题</span>
          </div>
          <p class="step-description">{{ currentStep ? currentStep.description : '' }}</p>
        </div>
        
        <!-- 根据步骤类型显示不同内容 -->
        <div class="step-content">
          <!-- 知识卡片 -->
          <div v-if="stepType === 'card' && card" class="card-content">
            <div class="card-header">
              <h3>{{ card.title }}</h3>
              <span :class="['difficulty-badge', getDifficultyClass(card.difficulty)]">
                {{ getDifficultyText(card.difficulty) }}
              </span>
            </div>
            <div class="card-body" v-html="card.content"></div>
            <div class="card-actions">
              <button 
                class="btn-mark-understood" 
                @click="markCardAsUnderstood"
                :disabled="stepCompleted"
              >
                {{ stepCompleted ? '已掌握' : '标记为已掌握' }}
              </button>
            </div>
          </div>
          
          <!-- 练习题 -->
          <div v-else-if="stepType === 'exercise' && exercise" class="exercise-content">
            <div class="exercise-header">
              <h3>{{ exercise.question }}</h3>
            </div>
            <div class="exercise-options">
              <div 
                v-for="(option, index) in exercise.options" 
                :key="index"
                :class="['option', {
                  'selected': selectedOption === index,
                  'correct': showAnswer && index === exercise.correctOption,
                  'incorrect': showAnswer && selectedOption === index && selectedOption !== exercise.correctOption
                }]"
                @click="selectOption(index)"
              >
                <span class="option-letter">{{ ['A', 'B', 'C', 'D'][index] }}</span>
                <span class="option-text">{{ option }}</span>
              </div>
            </div>
            <div v-if="showAnswer" class="answer-explanation">
              <h4>解析</h4>
              <p>{{ exercise.explanation }}</p>
            </div>
            <div class="exercise-actions">
              <button 
                v-if="!showAnswer" 
                class="btn-submit-answer" 
                @click="submitAnswer"
                :disabled="selectedOption === null"
              >
                提交答案
              </button>
              <button 
                v-else 
                class="btn-next" 
                @click="continueAfterExercise"
              >
                继续学习
              </button>
            </div>
          </div>
          
          <!-- 无内容 -->
          <div v-else class="no-content">
            <p>此步骤没有关联内容</p>
            <button class="btn-skip" @click="skipStep">跳过此步骤</button>
          </div>
        </div>
      </div>
      
      <!-- 底部导航 -->
      <div class="learning-navigation">
        <button 
          class="btn-prev" 
          @click="goToPreviousStep" 
          :disabled="currentStepIndex === 0"
        >
          上一步
        </button>
        
        <button 
          v-if="!isLastStep"
          class="btn-next" 
          @click="goToNextStep" 
          :disabled="!canProceed"
        >
          下一步
        </button>
        
        <button 
          v-else
          class="btn-complete" 
          @click="completeLearningPath"
        >
          完成学习
        </button>
      </div>
      
      <!-- 学习提示 -->
      <div class="learning-tips">
        <div class="tip-header" @click="showTips = !showTips">
          <h3>学习提示</h3>
          <span class="toggle-icon">{{ showTips ? '▼' : '▶' }}</span>
        </div>
        <div v-if="showTips" class="tip-content">
          <ul>
            <li><strong>按顺序学习</strong>：知识卡片按照科学的学习顺序排列，请按照顺序学习以获得最佳效果</li>
            <li>知识卡片：阅读并理解内容后，点击"标记为已掌握"继续</li>
            <li>练习题：选择正确答案并提交，查看解析后继续</li>
            <li>您可以随时暂停学习，系统会记录您的进度</li>
            <li>完成所有步骤后，您将获得学习路径的完成证明</li>
          </ul>
        </div>
      </div>
      
      <!-- 顺序学习提醒 -->
      <div v-if="!loading && !error && isFirstVisit" class="sequence-reminder">
        <div class="reminder-content">
          <h3>按顺序学习很重要</h3>
          <p>本系统设计的学习路径基于认知科学原理，按照从基础到高级的顺序安排知识点，确保您能够循序渐进地掌握知识。</p>
          <p>请按照系统推荐的顺序学习，避免跳跃式学习导致的知识断层。</p>
          <button @click="acknowledgeReminder" class="btn-acknowledge">我知道了，开始学习</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { learningPathApi } from '@/services/api';
import { cardApi } from '@/services/api';
import { exerciseApi } from '@/services/api';
import { useToast } from 'vue-toastification';

export default {
  name: 'LearningView',
  setup() {
    const route = useRoute();
    const router = useRouter();
    const toast = useToast();
    
    // 状态变量
    const loading = ref(true);
    const error = ref(null);
    const learningPath = ref(null);
    const userProgress = ref(null);
    const currentStepIndex = ref(0);
    const currentStep = ref(null);
    const currentStage = ref(null);
    const card = ref(null);
    const exercise = ref(null);
    const stepCompleted = ref(false);
    const selectedOption = ref(null);
    const showAnswer = ref(false);
    const showTips = ref(true);
    const startTime = ref(null);
    const isFirstVisit = ref(true);
    
    // 计算属性
    const stepType = computed(() => {
      if (!currentStep.value) return null;
      if (currentStep.value.cardId) return 'card';
      if (currentStep.value.exerciseId) return 'exercise';
      return null;
    });
    
    const totalSteps = computed(() => {
      if (!learningPath.value) return 0;
      return learningPath.value.stages.reduce((total, stage) => {
        return total + stage.steps.length;
      }, 0);
    });
    
    const progressPercentage = computed(() => {
      if (totalSteps.value === 0) return 0;
      return ((currentStepIndex.value + 1) / totalSteps.value) * 100;
    });
    
    const isLastStep = computed(() => {
      return currentStepIndex.value === totalSteps.value - 1;
    });
    
    const canProceed = computed(() => {
      if (stepType.value === 'card') {
        return stepCompleted.value;
      } else if (stepType.value === 'exercise') {
        return showAnswer.value;
      }
      return true;
    });
    
    // 方法
    const fetchLearningPath = async () => {
      loading.value = true;
      error.value = null;
      
      try {
        const pathId = route.params.id;
        const response = await learningPathApi.getById(pathId);
        learningPath.value = response.data;
        
        // 获取用户进度
        await fetchUserProgress(pathId);
        
        // 设置当前步骤
        setCurrentStep();
      } catch (err) {
        console.error('获取学习路径失败', err);
        error.value = '无法加载学习路径，请稍后再试';
      } finally {
        loading.value = false;
      }
    };
    
    const fetchUserProgress = async (pathId) => {
      try {
        const response = await learningPathApi.getNextStep(pathId);
        userProgress.value = response.data.progress;
        
        // 如果有未完成的步骤，跳转到该步骤
        if (response.data.nextStep) {
          const { stageIndex, stepIndex } = response.data.nextStep;
          
          // 计算全局步骤索引
          let globalStepIndex = 0;
          for (let i = 0; i < stageIndex; i++) {
            globalStepIndex += learningPath.value.stages[i].steps.length;
          }
          globalStepIndex += stepIndex;
          
          currentStepIndex.value = globalStepIndex;
        }
      } catch (err) {
        console.error('获取用户进度失败', err);
        // 如果获取进度失败，从第一步开始
        currentStepIndex.value = 0;
      }
    };
    
    const setCurrentStep = async () => {
      if (!learningPath.value) return;
      
      // 找到当前步骤所在的阶段和步骤
      let stepCount = 0;
      let found = false;
      
      for (const stage of learningPath.value.stages) {
        if (found) break;
        
        for (const step of stage.steps) {
          if (stepCount === currentStepIndex.value) {
            currentStep.value = step;
            currentStage.value = stage;
            found = true;
            break;
          }
          stepCount++;
        }
      }
      
      // 加载步骤相关内容
      await loadStepContent();
      
      // 检查步骤是否已完成
      checkStepCompletion();
      
      // 记录开始时间
      startTime.value = new Date();
    };
    
    const loadStepContent = async () => {
      if (!currentStep.value) return;
      
      // 重置状态
      card.value = null;
      exercise.value = null;
      selectedOption.value = null;
      showAnswer.value = false;
      
      // 加载卡片或练习
      if (currentStep.value.cardId) {
        try {
          const response = await cardApi.getById(currentStep.value.cardId);
          card.value = response.data;
        } catch (err) {
          console.error('加载卡片失败', err);
          toast.error('加载卡片内容失败，请稍后再试');
        }
      } else if (currentStep.value.exerciseId) {
        try {
          const response = await exerciseApi.getById(currentStep.value.exerciseId);
          exercise.value = response.data;
        } catch (err) {
          console.error('加载练习题失败', err);
          toast.error('加载练习题失败，请稍后再试');
        }
      }
    };
    
    const checkStepCompletion = () => {
      if (!userProgress.value || !currentStep.value) {
        stepCompleted.value = false;
        return;
      }
      
      // 查找当前步骤的进度
      for (const stageProgress of userProgress.value.stagesProgress) {
        for (const stepProgress of stageProgress.stepsProgress) {
          if (stepProgress.stepId === currentStep.value._id) {
            stepCompleted.value = stepProgress.status === 'completed';
            return;
          }
        }
      }
      
      stepCompleted.value = false;
    };
    
    const goToNextStep = async () => {
      if (currentStepIndex.value < totalSteps.value - 1) {
        // 更新当前步骤的进度
        await updateStepProgress('completed');
        
        // 前进到下一步
        currentStepIndex.value++;
        setCurrentStep();
      }
    };
    
    const goToPreviousStep = () => {
      if (currentStepIndex.value > 0) {
        currentStepIndex.value--;
        setCurrentStep();
      }
    };
    
    const markCardAsUnderstood = async () => {
      await updateStepProgress('completed');
      stepCompleted.value = true;
    };
    
    const selectOption = (index) => {
      if (showAnswer.value) return;
      selectedOption.value = index;
    };
    
    const submitAnswer = async () => {
      if (selectedOption.value === null) return;
      
      showAnswer.value = true;
      
      // 如果答案正确，标记为已完成
      if (selectedOption.value === exercise.value.correctOption) {
        await updateStepProgress('completed');
        stepCompleted.value = true;
      }
    };
    
    const continueAfterExercise = () => {
      // 如果答案错误，不自动前进到下一步
      if (selectedOption.value !== exercise.value.correctOption) {
        // 重置练习状态，让用户重新尝试
        selectedOption.value = null;
        showAnswer.value = false;
      } else {
        // 答案正确，前进到下一步
        goToNextStep();
      }
    };
    
    const skipStep = async () => {
      // 标记为已完成并前进
      await updateStepProgress('completed');
      goToNextStep();
    };
    
    const updateStepProgress = async (status) => {
      if (!learningPath.value || !currentStep.value) return;
      
      try {
        // 计算花费时间（分钟）
        const timeSpent = startTime.value ? Math.round((new Date() - startTime.value) / 60000) : 0;
        
        await learningPathApi.updateProgress(learningPath.value._id, {
          stepId: currentStep.value._id,
          status,
          timeSpent
        });
      } catch (err) {
        console.error('更新进度失败', err);
        toast.error('更新学习进度失败，请稍后再试');
      }
    };
    
    const completeLearningPath = async () => {
      // 更新最后一步的进度
      await updateStepProgress('completed');
      
      toast.success('恭喜您完成学习路径！');
      
      // 跳转到学习路径详情页
      router.push(`/learning-paths/${learningPath.value._id}`);
    };
    
    const goBack = () => {
      router.push(`/learning-paths/${learningPath.value._id}`);
    };
    
    // 难度处理方法
    const getDifficultyClass = (difficulty) => {
      const difficultyMap = {
        1: 'easy',
        2: 'medium',
        3: 'hard'
      };
      return difficultyMap[difficulty] || 'medium';
    };
    
    const getDifficultyText = (difficulty) => {
      const difficultyMap = {
        1: '简单',
        2: '中等',
        3: '困难'
      };
      return difficultyMap[difficulty] || '中等';
    };
    
    // 确认提醒
    const acknowledgeReminder = () => {
      isFirstVisit.value = false;
      // 存储到本地存储，避免重复显示
      localStorage.setItem('sequence_reminder_shown', 'true');
    };
    
    // 生命周期钩子
    onMounted(() => {
      // 检查是否已经显示过提醒
      if (localStorage.getItem('sequence_reminder_shown')) {
        isFirstVisit.value = false;
      }
      
      fetchLearningPath();
    });
    
    // 监听路由变化，重新加载数据
    watch(() => route.params.id, (newId, oldId) => {
      if (newId !== oldId) {
        fetchLearningPath();
      }
    });
    
    return {
      loading,
      error,
      learningPath,
      currentStepIndex,
      currentStep,
      currentStage,
      card,
      exercise,
      stepCompleted,
      selectedOption,
      showAnswer,
      showTips,
      stepType,
      totalSteps,
      progressPercentage,
      isLastStep,
      canProceed,
      fetchLearningStep: fetchLearningPath,
      goToNextStep,
      goToPreviousStep,
      markCardAsUnderstood,
      selectOption,
      submitAnswer,
      continueAfterExercise,
      skipStep,
      completeLearningPath,
      goBack,
      getDifficultyClass,
      getDifficultyText,
      isFirstVisit,
      acknowledgeReminder
    };
  }
};
</script>

<style scoped>
.learning-view-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top: 4px solid #3498db;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-message {
  text-align: center;
  padding: 30px;
  background-color: #fff3f3;
  border-radius: 8px;
  margin: 20px 0;
}

.btn-retry {
  background-color: #e74c3c;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

/* 进度条样式 */
.progress-bar-container {
  margin-bottom: 20px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.back-button {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #3498db;
}

.back-icon {
  margin-right: 5px;
}

.progress-text {
  font-size: 14px;
  color: #555;
}

.current-step {
  font-weight: bold;
  color: #3498db;
}

.stage-name {
  margin-left: 10px;
  font-style: italic;
}

.progress-bar {
  height: 8px;
  background-color: #eee;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: #3498db;
  transition: width 0.3s ease;
}

/* 主内容区域 */
.learning-main {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 30px;
  margin-bottom: 20px;
}

.step-header {
  margin-bottom: 30px;
}

.step-header h1 {
  margin-bottom: 10px;
  color: #2c3e50;
}

.step-meta {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
}

.estimated-time {
  color: #7f8c8d;
  font-size: 14px;
}

.step-type {
  background-color: #3498db;
  color: white;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.step-description {
  color: #555;
  font-size: 16px;
}

/* 卡片内容 */
.card-content {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.difficulty-badge {
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: white;
}

.difficulty-badge.easy {
  background-color: #2ecc71;
}

.difficulty-badge.medium {
  background-color: #f39c12;
}

.difficulty-badge.hard {
  background-color: #e74c3c;
}

.card-body {
  line-height: 1.6;
  font-size: 16px;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.card-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.btn-mark-understood {
  background-color: #2ecc71;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-mark-understood:disabled {
  background-color: #95e6b0;
  cursor: not-allowed;
}

/* 练习题内容 */
.exercise-content {
  margin-top: 20px;
}

.exercise-header {
  margin-bottom: 20px;
}

.exercise-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

.option {
  display: flex;
  align-items: center;
  padding: 15px;
  border-radius: 8px;
  background-color: #f9f9f9;
  cursor: pointer;
  transition: all 0.2s ease;
}

.option:hover {
  background-color: #eee;
}

.option.selected {
  background-color: #d6eaf8;
  border: 1px solid #3498db;
}

.option.correct {
  background-color: #d5f5e3;
  border: 1px solid #2ecc71;
}

.option.incorrect {
  background-color: #fadbd8;
  border: 1px solid #e74c3c;
}

.option-letter {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #3498db;
  color: white;
  border-radius: 50%;
  margin-right: 15px;
}

.option-text {
  flex: 1;
}

.answer-explanation {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  border-left: 4px solid #3498db;
}

.exercise-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.btn-submit-answer {
  background-color: #3498db;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-submit-answer:disabled {
  background-color: #a9cce3;
  cursor: not-allowed;
}

/* 无内容 */
.no-content {
  text-align: center;
  padding: 30px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.btn-skip {
  background-color: #7f8c8d;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 15px;
}

/* 导航按钮 */
.learning-navigation {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.btn-prev, .btn-next, .btn-complete {
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  border: none;
}

.btn-prev {
  background-color: #ecf0f1;
  color: #2c3e50;
}

.btn-prev:disabled {
  background-color: #f5f5f5;
  color: #bdc3c7;
  cursor: not-allowed;
}

.btn-next {
  background-color: #3498db;
  color: white;
}

.btn-next:disabled {
  background-color: #a9cce3;
  cursor: not-allowed;
}

.btn-complete {
  background-color: #2ecc71;
  color: white;
}

/* 学习提示 */
.learning-tips {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.tip-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #f5f5f5;
  cursor: pointer;
}

.tip-header h3 {
  margin: 0;
  font-size: 16px;
  color: #2c3e50;
}

.toggle-icon {
  color: #3498db;
}

.tip-content {
  padding: 15px 20px;
}

.tip-content ul {
  margin: 0;
  padding-left: 20px;
}

.tip-content li {
  margin-bottom: 8px;
  color: #555;
}

/* 顺序学习提醒样式 */
.sequence-reminder {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.reminder-content {
  background-color: white;
  border-radius: 8px;
  padding: 2rem;
  max-width: 500px;
  text-align: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.reminder-content h3 {
  color: #4CAF50;
  margin-bottom: 1rem;
  font-size: 1.5rem;
}

.reminder-content p {
  margin-bottom: 1rem;
  line-height: 1.6;
  color: #333;
}

.btn-acknowledge {
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 0.8rem 1.5rem;
  font-weight: bold;
  cursor: pointer;
  margin-top: 1rem;
  transition: background-color 0.2s;
}

.btn-acknowledge:hover {
  background-color: #45a049;
}
</style> 